package com.pai4j.netty.server;

import com.pai4j.common.constants.NettySocketConstants;
import com.pai4j.common.util.IPAddressUtil;
import com.pai4j.netty.server.common.PropertyLoader;
import com.pai4j.netty.server.config.RedisPool;
import com.pai4j.netty.server.config.RocketMQResource;
import com.pai4j.netty.server.config.properties.NacosConfig;
import com.pai4j.netty.server.config.properties.NettyServerProperties;
import com.pai4j.netty.server.config.NettyWebSocketServer;
import com.pai4j.netty.server.config.properties.RedisConfig;
import com.pai4j.netty.server.config.properties.RocketMQConfig;
import com.pai4j.netty.server.service.NettyNacosRegistry;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class NettyServerApplication {


    public static void main(String[] args) {

        // 设置当前启动环境配置参数
        // java -jar netty-server.jar -Denv=prod
        System.setProperty("env", "dev");

        NettyWebSocketServer nettyWebSocketServer = new NettyWebSocketServer();
        try {
            // 1. 预先加载系统配置
            initProperties();
            // 2. 启动netty server
            nettyWebSocketServer.start();
            log.error("netty server start success");
            // 3. 注册当前节点到nacos
            String ip = IPAddressUtil.getLocalIPv4Address();
            NettyNacosRegistry.registerInstance(NettySocketConstants.SERVICE_NAME,
                                                ip,
                                                NettyServerProperties.PORT,
                                                NettySocketConstants.CLUSTER_NAME);
        } catch (Exception e) {
            log.error("netty server start error", e);
            nettyWebSocketServer.stop();
            destroy();
        }
    }

    private static void initProperties() throws Exception {

        // 预加载配置
        PropertyLoader.init();

        // Nacos配置装配
        NacosConfig nacosConfig = NacosConfig.init();
        NettyNacosRegistry.init(nacosConfig);

        // 初始化Netty Server配置
        NettyServerProperties.init();

        // 初始化Redis配置
        RedisConfig redisConfig = RedisConfig.init();

        // 初始化Jedis链接池
        RedisPool.init(redisConfig);

        // 初始化RocketMQ配置
        RocketMQConfig rocketMQConfig = RocketMQConfig.init();
        // 启动RocketMQ生产者
        RocketMQResource.initProducer(rocketMQConfig);
        // 启动接收来自业务Server消息确认推送Consumer
        RocketMQResource.initConsumer(rocketMQConfig);
        // 启动来自集群其他Node确认消息消息推送的Consumer
        // （分布式下Channel共享问题，采用服务注册于直链方案)
        RocketMQResource.initIMMessageSendConsumer(rocketMQConfig);
    }

    private static void destroy() {

        RedisPool.destroy();

        PropertyLoader.destroy();
    }
}
